import * as types from '../constants/ActionTypes';
import Request from '../utils/request';

/**
*我的页面，所在4s店数据请求
*/

const fetchStoreInfo = callback => (dispatch) => {
  Request.get({
    url: '/dealer/salerinfo',
    success: (storeInfo) => {
      dispatch(getStoreInfo(storeInfo));
      if (callback) {
        callback();
      }
    },
    fail: () => {
      console.log('fail');
      dispatch(getStoreInfo({}));
    },
    error: () => {
      console.log('error');
      dispatch(getStoreInfo({}));
    },
  });
};

const changeStoreName = (storeName, callback) => (dispatch) => {
  Request.post({
    url: '/dealer/info',
    data: {
      name: storeName,
    },
    success: () => {
      dispatch(changeName(storeName));
      console.log('修改店铺名称成功！');
      if (callback) {
        callback();
      }
    },
    fail: () => {
      dispatch(changeName(''));
      console.log('修改店铺名称失败！');
    },
    error: () => {
      dispatch(changeName(''));
      console.log('修改店铺名称错误！');
    },
  });
};

const changeStoreAddress = storeAddress => (dispatch) => {
  Request.post({
    url: '/dealer/info',
    data: {
      address: storeAddress,
    },
    success: () => {
      dispatch(changeAddress(storeAddress));
      console.log('修改店铺地址成功！');
    },
    fail: () => {
      dispatch(changeAddress(''));
      console.log('修改店铺地址失败！');
    },
    error: () => {
      dispatch(changeAddress(''));
      console.log('修改店铺地址错误！');
    },
  });
};

const ChangeDiscount = (data, callback) => (dispatch) => {
  Request.post({
    url: '/dealer/salerinfo',
    data,
    contenttype: 'form',
    success: () => {
      dispatch(discount(data));
      console.log('修改优惠成功！');
      if (callback) {
        callback();
      }
    },
    fail: () => {
      dispatch(discount({}));
      console.log('修改优惠失败！');
    },
    error: () => {
      dispatch(discount({}));
      console.log('修改优惠错误！');
    },
  });
};


const getStoreInfo = storeInfo => ({
  type: types.STORE_INFO,
  storeInfo,
});

const changeName = storeName => ({
  type: types.STORE_NAME,
  storeName,
});

const changeAddress = storeAddress => ({
  type: types.STORE_ADDRESS,
  storeAddress,
});

const discount = changeDiscount => ({
  type: types.CHANGE_DISCOUNT,
  changeDiscount,
});

const changeUserName = userName => ({
  type: types.USER_NAME,
  userName,
});

const changeStore = store => ({
  type: types.STORE,
  store,
});

const changeStAddress = cAddress => ({
  type: types.CHANGE_ADDRESS,
  cAddress,
});

export {
 fetchStoreInfo,
 changeStoreName,
 changeStoreAddress,
 ChangeDiscount,
 changeUserName,
 changeStore,
 changeStAddress,
};
